#!/usr/bin/env python
# coding: utf-8
"""
准备工作：需要把705upgrade目录放在脚本执行的路径下
"""

import re
import os
import time
import datetime
import string
from upgrade_software import *

log_node_summary = "upgrade_summary"
log_node_fail = "upgrade_fail"
log_node_success = "upgrade_success"
log_file_not_existed = "the file:%s isn't existed\n"

log_connect_fail = "connect ip:%s failed\n"
log_delete_fail = "delete ip:%s slot:%s file:%s failed\n"
log_put_fail = "cd ip:%s backupsys:%s and put slot:%s file:%s failed\n"
log_md5_fail = "md5 ip:%s slot:%s file:%s failed\n"

log_connect_success = "connect ip:%s success\n"
log_delete_success = "delete ip:%s slot:%s file:%s success\n"
log_put_success = "cd ip:%s backupsys:%s and put slot:%s file:%s success\n"
log_md5_success = "md5 ip:%s slot:%s file:%s success\n"


log_summary_success = "ip:%s success\n"
log_summary_fail = "ip:%s fail\n"

class TestCase(UpgradeSoftware):
    """
    TestCase
    """
    OPTIONS = [
        {
            'opt' : '--cfgfile',
            'dest': 'cfgfile',
            'metavar' : 'PATH',
            'help' : 'the file of ip list configuration',
            'required' : False,
            'default' : "ip.txt"
        },
        {
            'opt' : '--path',
            'dest': 'path',
            'metavar' : 'PATH',
            'help' : 'the directory of 705upgrade',
            'required' : True,
            'default' : "D:\heavysmoker\workspace\suites\info_collect"
        },
        {
            'opt' : '--md5',
            'dest': 'md5',
            'metavar' : 'md5',
            'help' : 'the enable of md5 check',
            'required' : False,
            'default' : True
        },
    ]     
    
    def info_init(self):
        self.info_dic = {}
        
        self.log_node_summary = log_node_summary
        self.log_node_fail = log_node_fail
        self.log_node_success = log_node_success
        
        self.log_file_not_existed = log_file_not_existed 
        self.log_connect_fail = log_connect_fail
        self.log_delete_fail = log_delete_fail
        self.log_put_fail = log_put_fail
        self.log_md5_fail = log_md5_fail        
        
        self.log_connect_success = log_connect_success
        self.log_delete_success = log_delete_success
        self.log_put_success = log_put_success
        self.log_md5_success = log_md5_success        
        
        self.log_summary_success = log_summary_success
        self.log_summary_fail = log_summary_fail
              
        return True 
    
    #以node为关键字，把信息保存到info_dic[node]中。
    def info_show(self, node, info):
        if not self.info_dic.has_key(node):
            self.info_dic[node] = ""
        self.info_dic[node] += info + '\n'        
        return True    
            
    def info_file_save(self, ip):
        path = self.work_path+'//'
        
        for node in self.info_dic:
            info_list = open(path+node+'_'+self.worktime+'.txt','a')            
            info_list.write(self.info_dic[node])
            info_list.close()
            
        return True
    
    def get_iplist(self):
        iplist_filted = []                
        if os.path.isfile(os.getcwd()+r'/'+ self.iplistfile):
            iplist = open(os.getcwd()+r'/'+ self.iplistfile)
            #self.info_show(log_node_info, "The iplist file %s is existed."%(self.iplistfile)) 
        else:
            self.info_show(self.log_node_fail, self.log_file_not_existed%(self.iplistfile))            
            return iplist_filted 
        
        for line in iplist:
            if re.match(r'^\s*$', line) is not None : continue # 忽略空白行
            if re.match(r'^\s*#', line) is not None : continue # 忽略注释行            
            iplist_filted.append(line.strip('\n'))        
            
        iplist.close()
        
        return iplist_filted  
       
    def _execute(self):        
        self.work_path = self.options.path
        self.md5 = self.options.md5
        self.info_init()
        
        worktime = str(datetime.datetime.now())
        self.worktime = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        self.iplistfile = self.options.cfgfile
        
        upgrade_file_dic = {
        "OPCA"  : [
        [r"/tffs/sys", r"upgrade.txt",           self.work_path+r'/705upgrade',        r"upgrade.txt"],
        [r"/tffs/sys", r"tn705opca.img",         self.work_path+r'/705upgrade',        r"tn705opca.img"],            
        [r"/tffs/sys", r"mospec.dat",            self.work_path+r'/705upgrade',        r"mospec.dat"],
        [r"/tffs/sys", r"tbldata.dat",           self.work_path+r'/705upgrade',        r"tbldata.dat"],
        [r"/tffs/sys", r"tblspec.dat",           self.work_path+r'/705upgrade',        r"tblspec.dat"],
        [r"/tffs/sys", r"ZEBOS.CFG",             self.work_path+r'/705upgrade',        r"ZEBOS.CFG"],
        [r"/tffs/sys", r"snmpd.conf",            self.work_path+r'/705upgrade',        r"snmpd.conf"],
        [r"/tffs/sys", r"netring.ini",           self.work_path+r'/705upgrade',        r"netring.ini"],        
        [r"/tffs/sys", r"QTR6081V0.F([\da-f]+)", self.work_path+r'/705upgrade',        r"QTR6081V0.F([\da-f]+)"],            
        [r"/tffs/sys", r"QTR6082V0.F([\da-f]+)", self.work_path+r'/705upgrade',        r"QTR6082V0.F([\da-f]+)"],
        [r"/tffs/sys", r"QTR6082V1.F([\da-f]+)", self.work_path+r'/705upgrade',        r"QTR6082V1.F([\da-f]+)"],
        [r"/tffs/sys", r"qtr6083V0.F([\da-f]+)", self.work_path+r'/705upgrade',        r"qtr6083V0.F([\da-f]+)"],
        [r"/tffs/sys", r"tn705pos.img",          self.work_path+r'/705upgrade',        r"tn705pos.img"],
        [r"/tffs/sys", r"S6085G10.F([\da-f]+)",  self.work_path+r'/705upgrade',        r"S6085G10.F([\da-f]+)"],
        [r"/tffs/sys", r"S6085F16S.F([\da-f]+)", self.work_path+r'/705upgrade',        r"S6085F16S.F([\da-f]+)"],
        [r"/tffs/sys", r"S6085F1S.F([\da-f]+)",  self.work_path+r'/705upgrade',        r"S6085F1S.F([\da-f]+)"],
        [r"/tffs/sys", r"filelist.txt",          self.work_path+r'/705upgrade',        r"filelist.txt"],        
        ]          
        }        
        
        ip_list = self.get_iplist()         
        
        for ip in ip_list:
            upgrade_slot_dic = {"OPCA":     []   }
            self.set_ne_ip(0, ip)
            
            #get ne's two opca card's backup boot sys
            self.slot_backupsys_list=self.get_slot_backupsys_list(ip)
            
            #get ne's actual opca slot need to be upgraded, the first element is active opca,so ensure upgrade active opca first.
            if [] == self.slot_backupsys_list:
                self.info_show(self.log_node_summary, self.log_summary_fail%(ip))            
                continue
            for slot_backupsys in self.slot_backupsys_list:
                upgrade_slot_dic["OPCA"].append(slot_backupsys[0])
            
            #upgrade ne's opca slot.    
            if not self.upgrade_files(upgrade_file_dic, upgrade_slot_dic):
                self.info_show(self.log_node_summary, self.log_summary_fail%(ip))
                continue
            
            self.info_show(self.log_node_summary, self.log_summary_success%(ip))
           
        worktime = str(datetime.datetime.now())
        self.worktime_end = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        
        self.info_show(log_node_summary, "The upgrade file operation begin time %s "%(self.worktime))
        self.info_show(log_node_summary, "The upgrade file operation end time %s "%(self.worktime_end))
        
        ip = '0.0.0.0'
        self.info_file_save(ip) 
        return True
    
if __name__ == "__main__" :
    case = TestCase()
    case.execute()